<template>
    <div class="common-layout">
      <el-container>
        <el-header height="25%">
          <el-page-header :icon="null" @back="backout">
    <template #content>
      <div class="flex items-center">

        <span class="text-sm mr-2" style="color: var(--el-text-color-regular)">
          标签管理
        </span>
        <el-tag>admin</el-tag>
      </div>
    </template>
    <template #extra>
      <div class="flex items-center">
        <el-space :size="size" :spacer="spacer">
          <el-popover
      :width="300"
      popper-style="box-shadow: rgb(14 18 22 / 35%) 0px 10px 38px -10px, rgb(14 18 22 / 20%) 0px 10px 20px -15px; padding: 20px;"
    >
      <template #reference>
        <el-avatar :size="50" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
      </template>
      <template #default>
        <div
          class="demo-rich-conent"
          style="display: flex; gap: 16px; flex-direction: column"
        >
          <el-avatar
            :size="60"
            src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
            style="margin-bottom: 8px"
          />
          <div>
            <p
              class="demo-rich-content__name"
              style="margin: 0; font-weight: 500"
            >
              Admin
            </p>
            <p
              class="demo-rich-content__mention"
              style="margin: 0; font-size: 14px; color: var(--el-color-info)"
            >
              @beathub.com
            </p>
          </div>

          <p class="demo-rich-content__desc" style="margin: 0">
            生产队的驴正在加紧赶工......
          </p>
        </div>
      </template>
    </el-popover>
      </el-space>
        <el-button type="danger" plain class="ml-2" @click="logout">退出</el-button>
      </div>
    </template>
  </el-page-header>
  <el-divider content-position="right">管理员操作</el-divider>
  <div class=box>    <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="标签名称">
      <el-input v-model="formInline.tagname" placeholder="标签名称模糊查询" clearable />
    </el-form-item>
    <el-form-item>
    <el-button type="danger" @click="btnQuery"><i class="iconfont icon-chaxun"></i></el-button>
    </el-form-item>
    <el-form-item>
    <el-button type="danger" @click="btnAddDialog"><i class="iconfont icon-tianjia2"></i></el-button>
    </el-form-item>
    <el-form-item>
    <el-popconfirm
        confirm-button-text="是"
        cancel-button-text="否"
        :icon="InfoFilled"
        icon-color="#626AEF"
        title="你确定要删除吗?"
        @confirm="deleteClick()"
        >
    <template #reference>
      <el-button type="danger"><i class="iconfont icon-lajitong"></i></el-button>
      </template>
  </el-popconfirm>
    </el-form-item>
   </el-form>
    </div>
  </el-header>
    <!-- 此为用户信息管理头部 -->
        <el-main>
        <!-- 页面主体显示内容 -->
      <el-row>
        <el-col :span="6" v-for="(item, index) in tableData" :key="index">
          <br><br>
          <el-checkbox v-model="item.selected" class="ml-2" >
          <el-button plain class="ml-2" type="default" size="large" @click="updateDialog(item.tagid)">
            <div style="display: flex; align-items: center;">
              <el-icon><timer /></el-icon>
              <span style="margin-left: -10px">{{ item.tagname }}</span>
            </div>
          </el-button>
          </el-checkbox>
        </el-col>
      </el-row>


    <!-- <div class="delete"> -->
     <!-- <el-table-column label="操作"> -->
       
          
        <!-- </template> -->
      <!-- </el-table-column> -->
    <!-- </div> -->

      <!-- 添加对话框 -->
<el-dialog v-model="dialogFormVisible" title="添加标签信息">
  <el-form :model="form">
      <el-form-item label="标签名称" :label-width="formLabelWidth">
        <el-input v-model="form.tagname" autocomplete="off" />
      </el-form-item>
      <el-form-item label="标签图片" :label-width="formLabelWidth">
        <el-upload
    class="avatar-uploader"
    action="http://localhost:8080/work/upload"
    :on-success="handleAvatarSuccess"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
        <!-- <el-input v-model="form.cover" autocomplete="off" /> -->
      </el-form-item>
    <el-form-item label="英文名称" :label-width="formLabelWidth">
        <el-input v-model="form.tagenglish" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="addTag">
          添加
        </el-button>
      </span>
    </template>
  </el-dialog>
       <!-- 修改对话框 -->
       <el-dialog v-model="updateDialogVisible" title="修改标签信息">
    <el-form :model="form">
      <el-form-item label="标签名称" :label-width="formLabelWidth">
        <el-input v-model="form.tagname" autocomplete="off" />
      </el-form-item>
      <el-form-item label="标签图片" :label-width="formLabelWidth">
        <img alt="暂无图片" width="300" height="350" :src="form.cover">
      </el-form-item>
      <el-form-item label="替换标签图片" :label-width="formLabelWidth">
        <el-upload
    class="avatar-uploader"
    action="http://localhost:8080/work/upload"
    :show-file-list="true"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
         >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>

      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="updateDialogVisible = false"
>取消</el-button>
        <el-button type="primary" @click="updateTag">
          修改  
        </el-button>
      </span>
    </template>
  </el-dialog>
        </el-main>
      </el-container>
    </div>
   </template>
   <script>
   import { ElMessage } from 'element-plus'
   //import { Timer } from '@element-plus/icons-vue'
   import { ArrowLeft } from '@element-plus/icons-vue'
   //import { de } from 'element-plus/es/locale'
   import { ref } from 'vue'
   import { h } from 'vue'
   import { ElDivider } from 'element-plus'
   import { ElUpload } from 'element-plus'
   import { Plus } from '@element-plus/icons-vue'
 
   export default{
    setup() {
      const size = ref(50)
      const spacer = h(ElDivider, { direction: 'vertical' })

      // 在这里可以进行其他的逻辑设置

      return {
        size,
        spacer,
        // 其他需要暴露给模板的属性
      }
    },

     data() {
      
       return {
        imageUrl: '',
         formInline: {
           tagname: ""
         },
         form: {},
         formLabelWidth:"140px",  //添加对话框宽
         dialogFormVisible:false,   //添加对话框
         updateDialogVisible:false, // 修改对话框
         tableData: [],
         Tag:{},
         tagData:[],
       }
     },
     mounted() {
       this.LoadData()           //加载标签信息
       this.LocalTagData() 

     },
     methods: {
      handleAvatarSuccess(response, uploadFile) {
    if (uploadFile && uploadFile.raw) {
      // 假设 response.data 包含了生成的图片路径
      this.form.cover = response; // 将生成的图片路径设置到 form.cover
      console.log('生成的图片路径：', this.form.cover);

      this.imageUrl = URL.createObjectURL(uploadFile.raw);
      console.log('图片URL：', this.imageUrl);
    } else {
      this.$message.error('上传失败');
    }
  },
    beforeAvatarUpload(rawFile) {
      if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('请上传图片为JPG格式!')
        return false
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片不可超过2MB!')
        return false
      }
      return true
    },
      center(){
      this.$router.push('admincenter')
    },
    logout() {
      this.$router.push('/');
    },
    backout() {
      this.$router.push('/welcome');
    },

       btnQuery() {
         console.log(this.formInline)
         this.LoadData()
       },
       LocalTagData(){  //加载标签信息数据
        this.$http.get("http://localhost:8080/tag/list").then((res)=>{
        this.TagData = res.data;
        console.log(res.data);
      }).catch((err)=>{
        console.log(err);
      })
      },
       LoadData() {              //重加载数据
         this.$http.get("http://localhost:8080/tag/list?tagname=" + this.formInline.tagname).then((res) => {
           this.tableData = res.data;
           console.log(res.data);
         }).catch((err) => {
           console.log(err);
         })
       },
       addTag(){    
        console.log(this.form);
        this.$http.post("http://localhost:8080/tag/add",this.form).then((res)=>{
              console.log(res.data);
              if(res.data==1){
                console.log("添加成功");
                this.form={},
                this.dialogFormVisible=false;
                this.imageUrl = "";
                this.LoadData()
                ElMessage({
                message: '添加成功',
                type: 'success',
                })
              }else{
                console.log("添加失败");
                this.LoadData()
                ElMessage({
                message: '添加失败',
                type: 'warning',
            }).catch((err)=>{
              // console.log(err);
            })
              }
      })
    },
       updateTag() {   //更新修改操作
            console.log(this.form);
            this.$http.post("http://localhost:8080/tag/update",this.form).then((res)=>{
              console.log(res.data);
              if(res.data==1){
                console.log("修改成功");
                this.form={},    //清空表单
                this.updateDialogVisible=false //关闭
                this.LoadData()   //重新加载
                this.imageUrl = "";

                ElMessage({
                message: '修改成功',
                type: 'success',
                })
              }else{
                console.log("修改失败");
                this.LoadData()
                ElMessage({
                message: '修改失败',
                type: 'warning',
            }).catch((err)=>{
              // console.log(err);
            })
              }
        })
      },
      async deleteClick() {    //删除操作
    const selectedItems = this.tableData.filter(item => item.selected);
    if (selectedItems.length > 0) {
      try {
        for (const selectedItem of selectedItems) {
          const tagid = selectedItem.tagid;

          // 发送删除请求到后端
          await this.$http.get(`http://localhost:8080/tag/del/${tagid}`);
          
          // 从前端数据中删除已被成功删除的项目
          const index = this.tableData.findIndex(item => item.tagid === tagid);
          if (index !== -1) {
            this.tableData.splice(index, 1);
          }
        }
        ElMessage({
                message: '删除成功',
                type: 'success',
                })
        console.log('选中项目已从数据库和界面上删除');
      } catch (error) {
        ElMessage({
                message: '删除失败',
                type: 'warning',
                })
        console.error('删除失败:', error);
      }
    } else {
      ElMessage({
                message: '请选择要删除的标签',
                type: 'warning',
                })
      console.log('请选择要删除的项目');
    }
},

       
       updateDialog(tagid) {   //修改操作，数据回显
        console.log(tagid);
        this.$http.get("http://localhost:8080/tag/get1/"+tagid).then((res)=>{
            console.log(res.data)
            this.form = res.data
      }).catch((err)=>{
            console.log(err);
      })
      this.updateDialogVisible = true
  },
    btnAddDialog(){       //添加按钮，跳出添加窗口
          this.dialogFormVisible = true //点击显示弹出框
      }
    }
}     


 

 </script>

<style>
.input-width {
  width: 40%;
  /* 设置宽度为100% */
  resize: none;
  /* 禁止调整大小 */
}

.box {
  position: relative;
  top: 20px;
}
.table-page{
  float:right;
  margin:12px
  }


.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>